from django.db import models


class City(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=10, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class DataCenter(models.Model):
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('name', 'city')

    def __str__(self):
        return f"{self.name} ({self.city})"


class Host(models.Model):
    OS_CHOICES = [
        ('linux', 'Linux'),
        ('windows', 'Windows'),
        ('macos', 'MacOS'),
    ]

    hostname = models.CharField(max_length=100, unique=True)
    ip_address = models.CharField(max_length=15)
    os_type = models.CharField(max_length=10, choices=OS_CHOICES)
    data_center = models.ForeignKey(DataCenter, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.hostname} ({self.ip_address})"


class HostPassword(models.Model):
    host = models.OneToOneField(Host, on_delete=models.CASCADE, related_name='password_info')
    root_password = models.CharField(max_length=100)
    last_changed = models.DateTimeField(auto_now=True)
    history = models.JSONField(default=list)  # Stores previous passwords with timestamps

    def __str__(self):
        return f"Password for {self.host}"


class DailyStat(models.Model):
    date = models.DateField()
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    data_center = models.ForeignKey(DataCenter, on_delete=models.CASCADE)
    host_count = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('date', 'city', 'data_center')

    def __str__(self):
        return f"{self.date}: {self.data_center} - {self.host_count} hosts"


class RequestLog(models.Model):
    path = models.CharField(max_length=255)
    method = models.CharField(max_length=10)
    status_code = models.IntegerField()
    duration = models.FloatField()  # in seconds
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.method} {self.path} - {self.status_code} ({self.duration}s)"